<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <!-- 引入样式 -->
        <link href="element/index.css" rel="stylesheet">
        <style>
            .el-header {
                background-color: #B3C0D1;
                color: #333;
                line-height: 60px;
            }

            .left{
                height: 30px;
                z-index: 2;
                width: 30%;
                padding-right: 10px;
                box-sizing: border-box;
            }
        </style>
    </head>
    <body>
        <div id="app">
            <el-container>
                <el-header style="text-align: right; font-size: 12px">
                    <el-dropdown>
                        <i class="el-icon-setting" style="margin-right: 15px"></i>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item>查看</el-dropdown-item>
                            <el-dropdown-item>新增</el-dropdown-item>
                            <el-dropdown-item>删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    <span>李超</span>
                </el-header>

                <el-main>
                    <!--<div style="text-align: center">
                        <el-button @click="showAddZkConfig = true" type="primary">新增zk服务器配置</el-button>
                    </div>-->
                    <div class="left">
                        <el-input size="mini" clearable placeholder="输入关键字进行过滤" v-model="treeFilterText"  class="input-with-select" >
                            <el-button slot="append" type="primary" icon="el-icon-plus" circle @click="showAddZkConfig = true" >
                                <span>新增zk服务器配置</span>
                            </el-button>
                        </el-input>
                    </div>
                    <el-tree
                            ref="tree"
                            :key="treeKey"
                            :expand-on-click-node="false"
                            :props="props"
                            :load="loadNode"
                            @node-click="clickNode"
                            lazy
                            node-key="name"
                            show-checkbox
                            v-show="showZkTree">
                            <span class="custom-tree-node" slot-scope="{ node, data }">
                                <span v-text="node.label"></span>
                                <span>
                                      <!--<el-button
                                              @click="() => append(data)"
                                              size="mini"
                                              type="text">
                                        Append
                                      </el-button>-->
                                      <el-button
                                              @click="() => removeNode(node, data)"
                                              size="mini"
                                              type="text">
                                        删除
                                      </el-button>
                                </span>
                           </span>
                    </el-tree>
                    <el-dialog :visible.sync="showAddZkConfig" title="zk服务器配置" width="30%">
                        <el-form :model="form">
                            <el-form-item :label-width="formLabelWidth" label="IP地址">
                                <el-input auto-complete="off" v-model="form.ip"></el-input>
                            </el-form-item>
                            <el-form-item :label-width="formLabelWidth" label="端口">
                                <el-input auto-complete="off" v-model="form.port"></el-input>
                            </el-form-item>
                        </el-form>
                        <div class="dialog-footer" slot="footer">
                            <el-button @click="checkConnect" round>连接测试</el-button>
                            <el-button @click="connect" type="primary">确 定</el-button>
                            <el-button @click="dialogZkConfig = false">取 消</el-button>
                        </div>
                    </el-dialog>
                </el-main>
            </el-container>
        </div>
        <!-- 先引入 Vue -->
        <script src="element/vue.js"></script>
        <!-- 引入组件库 -->
        <script src="element/index.js"></script>
        <script>
            let id = 1000;

            var vm = new Vue({
                el: '#app',
                data() {
                    return {
                        // config
                        localStorage:{
                            key: 'zk_server_config',
                        },

                        // dialog
                        showZkTree: true,
                        showAddZkConfig: false,

                        // data
                        serverList: [],
                        treeFilterText:'',
                        props:{
                            label:"name",
                            children: "childList",
                            isLeaf: 'leaf'
                        },
                        treeKey: '',    // 控制tree渲染的key

                        form: {
                            ip: '127.0.0.1',
                            port: '2181'
                        },
                        session: {
                            id: ''
                        },
                        formLabelWidth: '60px'
                    };
                },
                beforeCreate() {

                },
                //vue创建成功，此时html元素尚未挂载
                created() {
                    this.serverList = this.getZkServer();
                },
                //此时html元素已经挂载成功
                mounted() {

                },
                methods: {
                    // 连接测试
                    checkConnect() {
                        let addr = this.form.ip + ":" + this.form.port;
                        console.log("addr:" + addr);
                        axios({
                            method: 'post',
                            url: '/checkConnect',
                            data: {
                                addr: addr,
                            }
                        }).then(response => {
                            let data = response.data;
                            if (data) {
                                let connected = data.connected;
                                if (connected == true) {
                                    this.$message('连接成功');
                                } else {
                                    this.$message.error('连接失败');
                                }
                            } else {
                                alert("请求错误");
                            }
                        });
                    },
                    // 创建连接配置
                    connect() {
                        let addr = this.form.ip + ":" + this.form.port;
                        console.log("addr:" + addr);
                        axios({
                            method: 'post',
                            url: '/connect',
                            data: {
                                addr: addr,
                            }
                        }).then(response => {
                            let data = response.data;
                            if (data) {
                                let newConfig = {
                                    name:addr,
                                    addr:addr,
                                    path:"/",
                                };
                                if (this.addZkServer(newConfig)) {
                                    this.showAddZkConfig = false;
                                } else {
                                    this.$message.error('已存在相同zk配置');
                                }
                            } else {
                                alert("请求错误");
                            }
                        });
                    },
                    loadNode(node, resolve) {
                        if (node.level === 0) {
                            return resolve(this.serverList);
                        }
                        this.requestNode(node, resolve);
                    },
                    // 请求节点所有子节点
                    requestNode(node, resolve) {
                        let addr = node.data.addr;
                        let path = this.getAbsolutePath(node);
                        axios({
                            method: 'post',
                            url: '/listNode',
                            data: {
                                addr: addr,
                                path: path
                            }
                        }).then(response => {
                            let data = response.data;
                            if (data) {
                                let result = [];
                                data.forEach(item => result.push({
                                    name: item,
                                    addr: node.data.addr,
                                    path: item,
                                }));
                                resolve(result);
                            } else {
                                resolve([]);
                            }
                        });
                    },
                    // 获取绝对路径
                    getAbsolutePath(node) {
                        let parentPath = "";
                        if (node.level > 1 && node.parent) {
                            parentPath = this.getAbsolutePath(node.parent);
                        }
                        if (node.level <= 2) {
                            return parentPath + node.data.path;
                        } else {
                            return parentPath + "/" + node.data.path;
                        }
                    },
                    clickNode(obj, node) {
                        let path = this.getAbsolutePath(node);
                        axios({
                            method: 'post',
                            url: '/getNodeData',
                            data: {
                                sessionId: this.session.id,
                                path: path
                            }
                        }).then(function (response) {
                            let data = response.data;
                            console.log(data);
                        });
                    },
                    appendNode(data) {
                        const newChild = { id: id++, label: 'testtest', children: [] };
                        if (!data.children) {
                            this.$set(data, 'children', []);
                        }
                        data.children.push(newChild);
                    },
                    removeNode(node, data) {
                        this.$refs.tree.remove(node);
                        if (node.level === 1) {
                            this.removeLocStorageValue(data);
                        }
                    },
                    getLocalStorageValue() {
                        const storageKey = this.localStorage.key;
                        let storageValue = localStorage.getItem(storageKey);

                        if (storageValue && storageValue.indexOf('[') === 0) {
                            storageValue = JSON.parse(storageValue);
                        } else {
                            storageValue = [];
                        }
                        return storageValue;
                    },
                    appendLocStorageValue(data) {
                        const storageKey = this.localStorage.key;
                        const storageValue = this.getLocalStorageValue();
                        storageValue.push(data);
                        localStorage.setItem(storageKey, JSON.stringify(storageValue));
                    },
                    removeLocStorageValue(data) {
                        const storageKey = this.localStorage.key;
                        const storageValue = this.getLocalStorageValue();
                        const index = storageValue.findIndex(d => d.addr === data.addr);
                        storageValue.splice(index, 1);
                        localStorage.setItem(storageKey, JSON.stringify(storageValue));
                    },
                    addZkServer(newServer) {
                        const storageValue = this.getLocalStorageValue();
                        storageValue.forEach(server => {
                            if (server.addr == newServer.addr) {
                                return false;
                            }
                        });

                        this.appendLocStorageValue(newServer);
                        this.renderTree();
                        return true;
                    },
                    getZkServer(newItem, setArr) {
                        const storageKey = this.localStorage.key;
                        if (setArr) {
                            localStorage.setItem(storageKey, JSON.stringify(setArr));
                            return setArr;
                        }

                        let storageValue = localStorage.getItem(storageKey);

                        if (storageValue && storageValue.indexOf('[') === 0) {
                            storageValue = JSON.parse(storageValue);
                        } else {
                            storageValue = [];
                        }

                        //默认数据
                        if (storageValue.length == 0) {
                            storageValue.push({name: "127.0.0.1:2181", addr: '127.0.0.1:2181', path: '/'});
                            localStorage.setItem(storageKey, JSON.stringify(storageValue));
                        }
                        return storageValue;
                    },
                    // 刷新key值，重新渲染tree
                    renderTree() {
                        this.treeKey = +new Date();
                    },
                }
            });
        </script>
        <!-- axios -->
        <script src="element/axios.js"></script>
    </body>
</html>